package com.yunshipei.common;

import android.content.Context;
import android.content.SharedPreferences;
import android.text.TextUtils;

import com.google.gson.Gson;
import com.yunshipei.core.utils.SystemUtils;
import com.yunshipei.manager.YspPreferences;
import com.yunshipei.model.AppData;
import com.yunshipei.model.Company;
import com.yunshipei.model.EnterMailData;
import com.yunshipei.model.H5ContactModel;
import com.yunshipei.model.H5CustomModel;
import com.yunshipei.model.HomeAppsBean;
import com.yunshipei.model.MainExtraBean;
import com.yunshipei.model.ManagedSingleSignOn;
import com.yunshipei.model.UserInfo;
import com.yunshipei.utils.EncUtils;

import java.util.ArrayList;
import java.util.List;

public class UserLoginDataParser {

    private Context context;
    private SharedPreferences mPreferences;

    public UserLoginDataParser(Context context) {
        this.context = context;
        mPreferences = YspPreferences.getInstance().getSharedPreferences();
    }

    public MainExtraBean parse(String result) {
        Gson gson = new Gson();
        AppData appData = gson.fromJson(result, AppData.class);
        if (appData.data == null) {
            return null;
        }
        return createMainData(appData.data, result);
    }

    public MainExtraBean parse(String result, String dataJsStr) {
        mPreferences.edit().putString(Globals.YSP_DATA_JS, dataJsStr).apply();
        return parse(result);
    }

    private MainExtraBean createMainData(AppData.Data data, String result) {
        Company company = data.company;
        MainExtraBean mainExtraBean = new MainExtraBean();
        mainExtraBean.setToken(data.token);
        mainExtraBean.setUseContacts(company.isUseContacts());
        mainExtraBean.setUserInfo(data.userInfo);
        mainExtraBean.setOnLineHome(company.getHomePageURL());
        mainExtraBean.setCompanyTitle(data.companyTitle);
        mainExtraBean.setVpnInfos(data.vpns);
        mainExtraBean.setSsosModels(data.ssosModels);
        mainExtraBean.setThemeCode(company.getThemeCode());
        mainExtraBean.setManagerCode(data.managerCode);
        mainExtraBean.setTopId(data.topId);
        //处理首页资源的路径
        AppData.Data.DataJSApps.AppIncremental appIncremental = data.dataJSApps.appIncremental;
        if (appIncremental == null) {
            String homePage = data.homePage;
            if (!TextUtils.isEmpty(homePage)) {
                String homeResDir = homePage.substring(homePage.lastIndexOf("/") + 1).replace(".zip", "");
                mainExtraBean.setHomeResDir(homeResDir);
            }
        } else {
            boolean isPad = SystemUtils.isPad(context);
            String homeDir = "homePage" + (isPad ? appIncremental.enterplorerPadHomePage.incrementalVersion : appIncremental.enterplorerHomepage.incrementalVersion);
            mainExtraBean.setHomeResDir(homeDir);
        }
        //设置h5版的通讯录和我的
        int managerCode = data.managerCode;
        if (managerCode >= 2) {
            AppData.Data.DataJSApps.AppIncremental.EnterplorerAddressBookpage enterplorerAddressBookpage = data.dataJSApps.appIncremental.enterplorerAddressBookpage;
            H5ContactModel h5ContactModel = new H5ContactModel(enterplorerAddressBookpage.incrementalVersion, enterplorerAddressBookpage.downloadUrl);
            mainExtraBean.setH5ContactModel(h5ContactModel);
            AppData.Data.DataJSApps.AppIncremental.EnterplorerMepage enterplorerMepage = data.dataJSApps.appIncremental.enterplorerMepage;
            H5CustomModel h5CustomModel = new H5CustomModel(enterplorerMepage.incrementalVersion, enterplorerMepage.downloadUrl);
            mainExtraBean.setH5CustomModel(h5CustomModel);
        }

        //设置SSO
        ManagedSingleSignOn managedSingleSignOn = data.managedSingleSignOn;
        if (managedSingleSignOn != null && managedSingleSignOn.interval != -2) {
            mainExtraBean.setManagedSingleSignOn(data.managedSingleSignOn);
        }
        //处理九宫格每个app的信息
        List<AppData.Data.DataJSApps.GroupList> groupList = data.dataJSApps.groupList;
        List<HomeAppsBean> homeAppsBeens = parseDataJS(groupList);
        mainExtraBean.setHomeApps(homeAppsBeens);
        Company.DocSetting docSetting = company.docSetting;
        if (docSetting == null) {
            Company.DocSetting docS = new Company.DocSetting();
            docS.documentSecurity = 1;
            mainExtraBean.setDocSetting(docS);
        } else {
            mainExtraBean.setDocSetting(docSetting);
        }

        //3、本地数据保存
        //3.1、dataJs保存本地
        SharedPreferences.Editor preferenceEditor = mPreferences.edit();
        //3.2、是否修改过初始密码
        int state = data.initState;
        preferenceEditor.putBoolean(Globals.PASSWORD_STATE, 0 == state);
        //3.3、其他数据,很大一部分不知道干啥的
        UserInfo userInfo = data.userInfo;
        preferenceEditor.putString(Globals.YSP_TOKEN, data.token)
                .putString(Globals.YSP_TOP_ID, data.topId)
                .putString(Globals.UUID, userInfo.getUuid())
                .putString(Globals.YSP_DEPARTMENT_ID, data.userInfo.getDepartmentId())
                .putString(Globals.YSP_USER_INFO_FOR_WEBVIEW, data.userInfo.toString())
                .putString(Globals.YSP_COMPANY_ID, data.userInfo.getCompanyId())
                .putString(Globals.YSP_USER_EMAIL, data.userInfo.getEmail())
                .putString(Globals.YSP_USER_NICK_NAME, data.userInfo.getName())
                .putBoolean(Globals.USE_MANAGER_RUN_TIMES, company.useManagerDownloadRunTimes);

        //5、邮箱数据保存
        boolean emailAvailable = false;
        for (HomeAppsBean homeAppsBean : homeAppsBeens) {
            if (homeAppsBean.getAppURL().equals("enterplorer://email/")) {
                EnterMailData mailData = homeAppsBean.getEnterMailData();
                if (mailData != null) {
                    emailAvailable = true;
                    preferenceEditor.putString("yunshipei_email_type", mailData.getEmailType());
                    preferenceEditor.putString("yunshipei_email_incoming", mailData.getGetServer());
                    preferenceEditor.putBoolean("yunshipei_email_incoming_ssl", mailData.isUseSSLGet());
                    preferenceEditor.putInt("yunshipei_email_incoming_port", mailData.getGetPort());
                    preferenceEditor.putString("yunshipei_email_outgoing", mailData.getSendServer());
                    preferenceEditor.putInt("yunshipei_email_outgoing_port", mailData.getSendPort());
                    preferenceEditor.putBoolean("yunshipei_email_outgoing_ssl", mailData.isUseSSLSend());
                    preferenceEditor.putBoolean("yunshipei_email_use_at", mailData.isUseAt());
                }
                break;
            }
        }
        preferenceEditor.putBoolean(Globals.YSP_EMAIL_AVAILABLE, emailAvailable);
        preferenceEditor.putBoolean(Globals.YSP_HAS_CONTACTS, company.isUseContacts());
        preferenceEditor.putString(Globals.YSP_SSO_OBJECT, new Gson().toJson(data.ssosModels));
        //加密存储登录数据
        preferenceEditor.putString(Globals.SP_LOGIN_DATA, EncUtils.encrypt(userInfo.getUuid(), result.getBytes())).apply();
        return mainExtraBean;
    }

    /**
     * @param result dataJS的内容
     */
    public List<HomeAppsBean> dataJS2HomeApps(String result) {
        Gson gson = new Gson();
        AppData.Data.DataJSApps apps = gson.fromJson(result, AppData.Data.DataJSApps.class);
        return parseDataJS(apps.groupList);
    }

    private List<HomeAppsBean> parseDataJS(List<AppData.Data.DataJSApps.GroupList> groupList) {
        List<HomeAppsBean> homeApps = new ArrayList<>();
        for (AppData.Data.DataJSApps.GroupList group : groupList) {
            List<HomeAppsBean> temps = group.homeAppsBeans;
            if (temps != null && temps.size() > 0) {
                homeApps.addAll(temps);
            }
        }
        return homeApps;
    }
}
